/*
 * @Description: 电子文件级
 * @Author: Zzt
 * @Date: 2022-12-28 11:41:38
 * @LastEditTime: 2023-01-06 16:43:17
 */

import { useEffect, useState } from 'react';
import { IDownLevelParams } from '@/api/archives/archives';
import { isNullObj } from '@/utils';
import { useArchiveCollectionContext } from '../../contexts/ArchiveCollectionContext';
import ERecordOperates from './ERecordOperates';
import CommonTableWrap from '../CommonTableWrap';
import type { IPageQuery } from '@/interfaces/global';

interface IERecordLevelProps {
  levelParams: any;
  selectChange?: any;
  data: any;
}

const ERecordLevel = (props: IERecordLevelProps) => {
  const { selectChange, data, levelParams } = props;
  const { eRecordsData, getERecords } = useArchiveCollectionContext();

  const [selectItems, setSelectItems] = useState<number[]>([]);
  // 表格加载
  const [loading, setLoading] = useState(false);
  // 总条目数
  const [total, setTotal] = useState(0);
  // 表格请求参数
  const [listQuery, setListQuery] = useState<IPageQuery<IDownLevelParams>>({
    pageNo: 1,
    pageSize: 10,
    param: null
  });

  useEffect(() => {
    if (levelParams && !isNullObj(levelParams)) {
      setListQuery((state: any) => {
        return {
          ...state,
          param: {
            ...levelParams,
            downLevelId: data.row_id
          }
        };
      });
    }
  }, [levelParams, data]);

  useEffect(() => {
    if (listQuery?.param && !isNullObj(listQuery.param)) {
      setLoading(true);
      getERecords(listQuery)
        .then((res: any) => {
          setTotal(res?.totalCount);
        })
        .finally(() => {
          setLoading(false);
        });
    }
  }, [listQuery]);

  /**
   * @description 选中条目方法
   * @param {number} record 页码
   */
  const onSelectChange = (record: any) => {
    selectChange && selectChange(eRecordsData.downLevel, record, eRecordsData.fieldList);
  };

  /**
   * @description 切换页码触发
   * @param {number} page 页码
   * @param {number} pageSize 每页条目数
   */
  const pageChange = (page: number, pageSize: number) => {
    setListQuery((state) => ({
      ...state,
      pageNo: page,
      pageSize
    }));
  };

  return (
    <CommonTableWrap
      title="电子文件级"
      operates={<ERecordOperates selectItems={selectItems} data={data} levelParams={levelParams} />}
      list={eRecordsData?.data || []}
      fieldList={eRecordsData?.fields || []}
      selectItems={selectItems}
      loading={loading}
      pagination={{
        current: listQuery.pageNo,
        pageSize: listQuery.pageSize,
        total,
        showTotal: (total) => `共 ${total} 条`,
        onChange: pageChange
      }}
      setSelectedItem={setSelectItems}
      selectChange={onSelectChange}
    />
  );
};

export default ERecordLevel;
